import logger from '../lib/Log4js';
import * as rp from 'request-promise';
import env from './../config/env';
import * as crypto from 'crypto';
import * as moment from 'moment';
import { UserInfoVo } from "./UserInfoVo";
import * as Url from 'url';
export class DTalkApi {
    url: string = 'https://open.dingtalk.com';
    // noncestr: string = 'Zn4zmLFKD0wzilzM';
    ticket: string;
    expires: number;
    access_token: string;
    expires_token: number;
    corpsecret:string='C9U5QM7k5cfZ898mLNEzxKt5aWj5XAq8aHFd5efoFSI0Q3YjTZ7-H6PsDQ84yOm2';
    corpid:string='ding42dbaee1aebac5d535c2f4657eb6378f';
    async getAccessToken() {
        if (!this.expires_token || this.expires_token < Date.now() + 20 * 60 * 100) {//提前20分钟获取 access_token
            console.log("getAccessToken 向钉钉服务器获取 accessToken ");
            //let rt = await rp.get(`https://oapi.dingtalk.com/gettoken?corpid=${env.corpId}&corpsecret=${env.corpsecret}`, { json: true })
            let rt = await rp.get(`https://oapi.dingtalk.com/gettoken?corpid=${this.corpid}&corpsecret=${this.corpsecret}`, { json: true })
            if (rt.errcode === 0) {
                this.access_token = rt.access_token;
                this.expires_token = Date.now() + 7200 * 1000;
                // await authCorp.save();
                return rt.access_token;
            } else {
                console.log('error.....', rt);
                // log4js.getLogger('log_error').error(rt);
            }
        } else {

            return this.access_token;
        }
    }

    async getJsapi_ticket() {
        if (!this.ticket || new Date().getTime() > this.expires) {//提前20分钟获取 access_token
            let rt = await rp.get(`http://weixin.seeyon.com/dingding/getDingTiket/${env.corpId}/${env.corpsecret}`)
            var json = JSON.parse(rt)[0];
            this.ticket = json.token;
            // console.log(this.access_token);
            // var deadline = json.expires;
            // console.log(deadline);
            this.expires = json.expires;
            //console.log(this.expires_token);
            // await authCorp.save();
            return this.ticket;

        } else {
            return this.ticket;
        }

       
    }


    async getSign(nonceStr: string, timeStamp: number, origUrl: string) {
        let ticket = await this.getJsapi_ticket();
        var origUrlObj = Url.parse(origUrl);
        delete origUrlObj['hash'];
        var newUrl = Url.format(origUrlObj);
        var plain = 'jsapi_ticket=' + ticket +'&noncestr=' + nonceStr +'&timestamp=' + timeStamp +'&url=' + newUrl;
        console.log(plain);
        var sha1 = crypto.createHash('sha1');
        sha1.update(plain, 'utf8');
        var signature = sha1.digest('hex');
        return signature;
    }

    //获取部门列表
    async deptList(id_: any) {
        let id:string=id_ || '';
        let ACCESS_TOKEN = await this.getAccessToken();
        let json = await rp.get(`https://oapi.dingtalk.com/department/list?access_token=${ACCESS_TOKEN}&id=${id}`,
            { json: true });
        if (json.errcode === 0) {
            return json;
        } else {
            console.log('deptList_Error',json)
            throw json.errmsg;
        }
    }
    
    //获取所有子部门的id列表
    async getSondepIdList(id: String, fetch_child:boolean) {
        let ACCESS_TOKEN = await this.getAccessToken();
        let json = await rp.get(`https://oapi.dingtalk.com/department/list?access_token=${ACCESS_TOKEN}&id=${id}&fetch_child=${fetch_child}`,
            { json: true });
        if (json.errcode === 0) {
            let deptData: number[] = []
            let detpNames: string[] = []
            let dept:any[]=[]
            json.department.map(item => {
                deptData.push(item.id)
                detpNames.push(item.name)
                dept.push({
                   id: item.id,//部门id
                    name:item.name//部门名称
                })
            })
            return { department: deptData, deptNames: detpNames ,dept:dept}
        } else {
            console.log('getSondepIdList_Error',json)
            throw json.errmsg;
        }
    }

    //获取部门详情
    async getDeptDetail(id: String) {
        let ACCESS_TOKEN = await this.getAccessToken();
        let json = await rp.get(`https://oapi.dingtalk.com/department/get?access_token=${ACCESS_TOKEN}&id=${id}`,
            { json: true });
        if (json.errcode === 0) {
            return json;
        } else {
            return null
        }
    }

    //获取员工详情
    async getUserDetail(id: String) {
        let ACCESS_TOKEN = await this.getAccessToken();
        let json = await rp.get(`https://oapi.dingtalk.com/user/get?access_token=${ACCESS_TOKEN}&userid=${id}`,
            { json: true });
        if (json.errcode === 0) {
            return json;
        } else {
            return null
        }
    }

    //获取部门下的所有员工列表
    async getUserList(id: String) {
        let ACCESS_TOKEN = await this.getAccessToken();
        let json = await rp.get(`https://oapi.dingtalk.com/user/simplelist?access_token=${ACCESS_TOKEN}&department_id=${id}`,
            { json: true });
        if (json.errcode === 0) {
            return json;
        } else {
            console.log('getUserList_Error',json)
            throw json.errmsg;
        }    
    }
   
    //获取部门成员详情
    async getDeptEmplDetail(id: String) {
        let ACCESS_TOKEN = await this.getAccessToken();
        let json = await rp.get(`https://oapi.dingtalk.com/user/list?access_token=${ACCESS_TOKEN}&department_id=${id}`,
            { json: true });
        if (json.errcode === 0) {
            return json;
        } else {
            console.log('getDeptEmplDetail_Error',json)
            throw json.errmsg;
        }    
    }
   
    //发送消息
    async sendMsg(OA: any) {
        let access_token = await this.getAccessToken();
        let json = await rp.post(`https://oapi.dingtalk.com/message/send?access_token=${access_token}`,
            {
                body: OA, json: true
            });
        if (json.errcode === 0) {
            return json;
        } else {
            throw json.errmsg;
        }
    }

    async getUserInfo(code: string): Promise<UserInfoVo> {
        let accessToken = await this.getAccessToken();
        let json = await rp.get(`https://oapi.dingtalk.com/user/getuserinfo?access_token=${accessToken}&code=${code}`, { json: true });
        if (json.errcode === 0) {
            return json as UserInfoVo;
        } else {
            console.log("getUserInfo", json);
            return null;//免登失败
        }
    }












   
    //查询指定用户的所有上级父部门路径
    async list_parent_depts(userid:string){
        let access_token = await this.getAccessToken();
        let json = await rp.get(`https://oapi.dingtalk.com/department/list_parent_depts?access_token=${access_token}&userId=${userid}`,
        { json: true });
        if (json.errcode === 0) {
            return json;
        }else{
            throw json.errmsg;
        }
    }
    //查询部门的所有上级父部门路径
    async get_parent(id: number) {
        let ACCESS_TOKEN = await this.getAccessToken();
        let json = await rp.get(`https://oapi.dingtalk.com/department/list_parent_depts_by_dept?access_token=${ACCESS_TOKEN}&id=${id}`,
            { json: true });
        if (json.errcode === 0) {
            return json;
        } else {
            throw json.errmsg;
        }
    }

    // 获取角色列表
    async getRolesList() {
        // let access_token = await dTalkApiUtil.getAccessToken();
        let access_token = await this.getAccessToken();
        let body = `format=json&method=dingtalk.corp.role.list&partner_id=apidoc&session=${access_token}&timestamp=${moment().format('YYYY-MM-DD HH:mm:ss')}&v=2.0&size=100`
        let data = await rp.post('https://eco.taobao.com/router/rest?' + body, {

        })
        return data;
    }

    //获取角色的员工列表
    async getRoleUsers(roleId: string) {
        // let ACCESS_TOKEN = await dTalkApiUtil.getAccessToken();
        let ACCESS_TOKEN = await this.getAccessToken();
        let json = await rp.post('https://eco.taobao.com/router/rest',
            {

                form: {
                    format: "json",
                    v: "2.0",
                    timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
                    session: ACCESS_TOKEN,
                    partner_id: "apidoc",
                    method: "dingtalk.corp.role.simplelist",
                    role_id: roleId
                }, json: true
            });

        if (json.dingtalk_corp_role_simplelist_response.result.list.emp_simple_list) {
            return json.dingtalk_corp_role_simplelist_response.result.list.emp_simple_list;
        }else{
            console.log(json.error_response);
            logger.errorLogger().error(json.error_response);
        }
    }

   
}
let dTalkApi = new DTalkApi();
export default dTalkApi;

